﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.IO.Ports;

namespace PowerMonitor.BaseCtrl
{
    public enum ChannelType // 通道类型
    {
        COM,
        CAN,
        TCP,
        UDP,
        OPC,  
    }
    public abstract class Channel  // 通道基类
    {
        public chlPara baseChlPara { get; set; }            // 通道参数 该属性主要是方便访问基本参数
        private int _PollingTime = 250;   // 轮询周期
        public int PollingTime
        {
            get { return _PollingTime; }
            set { if (value > 80)_PollingTime = value; }
        } 
        public abstract bool StartPolling();                // 开始轮询
        public abstract void StopPolling();                 // 停止轮询
        public abstract bool GetChannelState();             // 获取通道状态（线程是否运行）
        public abstract int GetDevicesCnt();                // 获取通道下挂载的设备总数 
        public abstract BaseDevice GetDevByIndex(int index);   // 获取index处的设备 没有这返回null
        public abstract bool InsertFrame(object InsertContent);    // 插帧发送
        public abstract bool InsertFrame(int devId, List<DevDataItem> DataList);
        public abstract int GetInsertFrameCnt();
        //public List<BaseDevice> m_BaseDevList = new List<BaseDevice>();    // 装置列表
        //public abstract bool SendBlock(byte[] bData);       // 发送数据
        //public abstract byte[] ReadBlock();                 // 接收数据
    }
    abstract public class chlPara
    {
        protected int _ChannelId = 0;
        public string ChannelName { get; set; }     // 通道名称
        public  int ChannelId
        {
            get { return _ChannelId; }
            set { if (value >= 0 && value < 100000) _ChannelId = value;} 
        }
        //public int PollingTime { get; set; }        // 轮询周期
        public string ChannelPara { get; set; }         // 通道参数
        public bool isWorking = true;
    }
    #region 串口通信
    public class ComPara : chlPara
    {
        private int _TimeOut = 20;        // 超时时间 一帧之中的两个字节接收时间间隔
        public int iTimeOut  // 超时时间
        {
            get { return _TimeOut; }
            set 
            {
                if (value > 10)
                {
                    ComPort.ReadTimeout = value;
                    _TimeOut = value; 
                }
                else
                {
                    ComPort.ReadTimeout = 25;
                    _TimeOut = 25; 
                }
            } 
        }    
        public SerialPort ComPort  = new SerialPort();
        public new string ChannelPara
        {
            get
            { 
                return string.Format("{0},{1},{2},{3},{4},{5}",ComPort.PortName,ComPort.BaudRate,ComPort.Parity,ComPort.DataBits,ComPort.StopBits);
            }
        }
        public  ComPara(int ChlId,string strChlName)
        {
            _ChannelId = ChlId;
            ChannelName = strChlName;
        }
    }
    public class ComChannel : Channel
    {
        private ComPara _ChlPara;
        private BackgroundWorker ChannelThread; // 轮询线程
        public chlPara ChlPara
        {
            get { return _ChlPara; }
            set
            {
                if (value is ComPara)
                {
                    _ChlPara = value as ComPara;
                }
                else
                {
                    Exception ex = new Exception("值类型错误！");
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 获取通道下挂载的设备总数 
        /// </summary>
        /// <returns></returns>
        public override int GetDevicesCnt()                
        {
            return 0;
        }
        /// <summary>
        /// 获取index处的设备 没有这返回null
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public override BaseDevice GetDevByIndex(int index)
        {
            return null;
        }
        public override bool InsertFrame(object InsertContent)
        {
            throw new NotImplementedException();
        }
        public override bool InsertFrame(int devId, List<DevDataItem> DataList)
        {
            throw new NotImplementedException();
        }
        public override int GetInsertFrameCnt()
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 开始轮询
        /// </summary>
        /// <returns></returns>
        public override bool StartPolling()
        {
            if (ChannelThread == null)
            {
                ChannelThread = new BackgroundWorker();
            }
            if (ChannelThread.IsBusy)
            {
                return false;
            }
            ChannelThread.WorkerSupportsCancellation = true;
            ChannelThread.DoWork += RunPollingThread;
            ChannelThread.RunWorkerCompleted += RunWorkerCompleted;
            ChannelThread.RunWorkerAsync();
            return  true;
        }
        /// <summary>
        /// 停止轮询
        /// </summary>
        public override void StopPolling()
        {
            if (ChannelThread == null)
            {
                return;
            }
            if (ChannelThread.IsBusy)
            {
                ChannelThread.CancelAsync() ;
            }
        }
        /// <summary>
        /// 获取通道状态（true运行 false 停止）
        /// </summary>
        /// <returns></returns>
        public override bool GetChannelState()
        {
            if (ChannelThread.IsBusy)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void RunPollingThread(Object sender,DoWorkEventArgs e)
        {

        }
        void RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
        {

        }
        /// <summary>
        /// 发送数据至传送缓冲区
        /// </summary>
        /// <param name="bData"></param>
        /// <returns></returns>
        public  bool SendBlock(byte[] bData)
        {
            if (bData == null || bData.Length ==0)
            {
                return false;
            }
            _ChlPara.ComPort.DiscardInBuffer();
            _ChlPara.ComPort.DiscardOutBuffer();
            _ChlPara.ComPort.Write(bData, 0, bData.Length);
           return true;
        }
        /// <summary>
        /// 取出接收缓冲区数据
        /// </summary>
        /// <returns></returns>
        public  byte[] ReadBlock()
        {
            List<byte> RecBytelist = new List<byte>();
            int iRec = 0;
            try
            {
                while (iRec != -1) // 测试发现没有出现-1  而是最后读取超时
                {
                    RecBytelist.Add((byte)iRec);
                    iRec = _ChlPara.ComPort.ReadByte(); // 超时会引发异常（接收第一个字节后超时,作为结束判断）
                }
            }
            catch (System.Exception ex) // 等待超时
            {
                Console.WriteLine(ex.Message);
                if (RecBytelist.Count > 0)
                {
                    return RecBytelist.ToArray();
                } 
                else
                {
                    return null;
                }
            }
            if (RecBytelist.Count > 0)
            {
                return RecBytelist.ToArray();
            }
            else
            {
                return null;
            }
        }
        public override string ToString()
        {
            return "ComPort_Channel";
        }
    }
   #endregion
}
